package menu_api

import (
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/ctype"
	"giv-vue-blog/models/res"
)

type ImageSort struct {
	ImageID uint `json:"image_id"`
	Sort    int  `json:"sort"`
}
type MenuRequest struct {
	Title         string      `json:"title" binding:"required" msg:"请完善菜单名称" structs:"title"`
	Path          string      `json:"path" binding:"required" msg:"请完善菜单路径" structs:"path"`
	Slogan        string      `json:"slogan" structs:"slogan"`
	Abstract      ctype.Array `json:"abstract" structs:"abstract"`
	AbstractTime  int         `json:"abstract_time" structs:"abstract_time"`
	BannerTime    int         `json:"banner_time" structs:"banner_time"`
	Sort          int         `json:"sort" binding:"required" msg:"请选择菜单序号" structs:"sort"`
	ImageSortList []ImageSort `json:"image_sort_list" structs:"-"` //具体图片的顺序
}

// MenuCreateView 创建菜单.
// @Summary 创建菜单
// @Description 创建菜单
// @Tags 菜单管理
// @Accept json
// @Produce json
// @Param menuRequest body MenuRequest true "Menu Request Payload"
// @Success 200 {string} string "菜单添加成功"
// @Failure 400 {object} string "请求失败"
// @Router /api/menu [post]
func (MenuApi) MenuCreateView(c *gin.Context) {
	var Menu MenuRequest
	err := c.ShouldBindJSON(&Menu)
	if err != nil {
		res.FailedWithError(err, &Menu, c)
		return
	}
	//0、重复判断 菜单的标题或者菜单的路径不能相同，否则就被判定为重复
	var menuList []models.MenuModel
	count := global.DB.Find(&menuList, "title=? or path=?", Menu.Title, Menu.Path).RowsAffected
	if count != 0 {
		res.FailedWithMsg("重复的菜单", c)
		return
	}
	//1、创建菜单数据入库
	menuModel := models.MenuModel{
		Title:        Menu.Title,
		Path:         Menu.Path,
		Slogan:       Menu.Slogan,
		Abstract:     Menu.Abstract,
		AbstractTime: Menu.AbstractTime,
		BannerTime:   Menu.BannerTime,
		Sort:         Menu.Sort,
	}
	err = global.DB.Create(&menuModel).Error
	if err != nil {
		global.Log.Error(err)
		res.FailedWithMsg("菜单添加失败", c)
		return
	}
	if len(Menu.ImageSortList) == 0 {
		res.OkWithMsg("菜单添加成功", c)
		return
	}
	//2、给第三张表menu_banner_models批量入库
	var menuBannerList []models.MenuBannerModel
	for _, sort := range Menu.ImageSortList {
		menuBannerList = append(menuBannerList, models.MenuBannerModel{
			MenuID:   menuModel.ID,
			BannerID: sort.ImageID,
			Sort:     sort.Sort,
		})
	}
	err = global.DB.Create(&menuBannerList).Error
	if err != nil {
		global.Log.Error(err)
		res.FailedWithMsg("菜单图片关联失败", c)
		return
	}
	res.OkWithMsg("菜单添加成功", c)
}
